<template>
  <view class="train-wrap">
    <!-- 训练组件 -->
    <kz-question 
      :questions="questions" 
      :questionCount="questionCount" 
      :pageCount="pageCount" 
      :currentPage="currentPage" 
      mode="TRAINING" 
      :trainType="trainType" 
      :viewMode="mode" 
      @loadQuestion="getQuestion"
      @nextQuestion="handleNextQuestion"
      @refresh="refreshPage"
      @questionAnswered="handleQuestionAnswered">
    </kz-question>
    
    <!-- toast提示 -->
    <tn-toast ref="toast"></tn-toast>
  </view>
</template>

<script>
export default {
  data () {
    return {
      cateId: 0,
      cateName: '',
      questions: [],
      questionCount: 0,
      pageCount: 20,
      currentPage: 0,
      lastPage: 0,
      mode: 'normal',
      trainType: 'normal'
    }
  },
  onLoad (e) {
    this.cateId = e.cateId
    this.cateName = e?.cateName || '题库练习'
    this.mode = e.mode
    this.trainType = e?.trainType || 'normal'
    
    // 设置导航栏标题
    uni.setNavigationBarTitle({
      title: this.cateName
    })
    
    // 开始加载数据
    if (this.mode === 'memory') {
      // 记忆模式 - 检查记忆位置
      const cacheKey = 'training' + '-' + this.cateId
      console.log('cacheKey',cacheKey)
      const memoryData = this.utils.getData(cacheKey)
      if (memoryData && memoryData.memory_index) {
        // 获取记忆位置并计算所需页数
        console.log('dfds',memoryData,memoryData.memory_index)
        const memoryIndex = memoryData.memory_index
        const neededPage = Math.ceil(memoryIndex / this.pageCount)
        this.getQuestion(1,neededPage * 20)
 
      } else {
        // 没有记忆数据，只加载第一页
        this.getQuestion()
      }
    } else {
      // 普通模式，只加载第一页
      this.getQuestion()
    }
  },
  methods: {
    // 处理题目作答事件
    handleQuestionAnswered(data) {
      // 获取是否回答正确
      const wrong = data && data.is_right === 'error' ? 1 : 0
      
      // 请求进度接口
      this.http('/Grade/progress', {
        cate_id: this.cateId,
        wrong: wrong
      }, 'post', false).catch(err => {
        console.error('进度记录请求失败:', err)
      })
    },

    // 刷新页面
    refreshPage() {
      // 清空当前数据
      this.questions = []
      this.currentPage = 0
      // 重新加载第一页
      this.getQuestion()
    },
    
    // 递归加载从startPage到endPage的所有页面
    loadPages(startPage, endPage) {
      if (startPage > endPage) return
      
      this.getQuestion(startPage, () => {
        if (startPage < endPage) {
          this.loadPages(startPage + 1, endPage)
        }
      })
    },
    
    // 获取试题
    getQuestion (page = 1, count = 20, callback = null) {
      console.log('getQuestion接收参数:', page, typeof count, typeof callback)
      
      // 如果count是函数，说明调用时将回调作为第二个参数传入
      if (typeof count === 'function') {
        callback = count
        count = 20
      }
      
      // 避免重复获取
      if (page <= this.currentPage || (this.lastPage && page > this.lastPage)) {
        if (typeof callback === 'function') {
          console.log('已加载或超出范围，直接执行回调')
          callback()
        }
        return
      }

      // 请求参数
      let params = {
        page: page,
        page_count: count,
        cate_id: this.cateId,
        mode: this.mode,
        type: 'train'
      }
      
      console.log('发起请求:', params)
      
      // 发送请求
      this.http('question/train', params, 'post', false).then(res => {
        
        console.log('请求成功，处理数据')
        
        if (res.code == 1) {
          // 更新分页信息
          this.questionCount = res.data.total
          this.lastPage = Math.ceil(res.data.total / this.pageCount)
          this.currentPage = page
          
          // 处理数据
          if (res.data.data && res.data.data.length > 0) {
            if (page === 1) {
              this.questions = res.data.data
            } else {
              this.questions = this.questions.concat(res.data.data)
            }
            console.log('数据加载成功，当前题目数:', this.questions.length)
          }

          // 积分提示
          let point = res.data.point
          if (point?.get_point > 0) {
            this.$refs.toast.show({
              title: "积分+" + point.get_point,
              content: point.type,
              imgUrl: "/static/toast/info-circle.png",
              icon: true,
              duration: 4000
            })
          }
        } else {
          console.error('请求失败:', res.msg)
          
          if (res.data && res.data.need_open_member) {
            uni.showModal({
              title: '提示',
              content: res.msg,
              confirmText: '前往开通',
              success: (res) => {
                if (res.confirm) {
                  this.utils.goto('/pages/user/member-center?from_train=1')
                } else if (res.cancel) {
                  this.utils.goback()
                }
              }
            })
          } else {
            uni.showToast({
              title: res.msg,
              icon: 'none'
            })
          }
        }
        
        // 执行回调 - 关键修复点：添加延时确保数据同步到子组件
        console.log('请求完成，准备执行回调，callback类型:', typeof callback)
        if (typeof callback === 'function') {
          console.log('添加200ms延时确保子组件数据更新')
          setTimeout(() => {
            console.log('延时后执行回调，当前题目总数:', this.questions.length)
            callback()
          }, 200)
        }
      }).catch(err => {
        console.error('请求出错:', err)
        
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        })
        
        // 即使出错也要执行回调
        if (typeof callback === 'function') {
          setTimeout(() => {
            callback()
          }, 100)
        }
      })
    },
    
    // 处理下一题事件
    handleNextQuestion() {
      // 如果接近当前页的末尾，预加载下一页
      if (this.currentPage < this.lastPage && 
          this.questions.length - (this.currentPage * this.pageCount) < 5) {
        this.getQuestion(this.currentPage + 1)
      }
    }
  }
}
</script>

<style>

</style>
